<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * Tiktok账户管理
 *
 * @icon fa fa-circle-o
 */
class Virtualmachinehidden extends Backend
{

    /**
     * Virtualmachinehidden模型对象
     * @var \app\admin\model\Virtualmachinehidden
     */
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Virtualmachinehidden;
        $this->view->assign("statusList", $this->model->getStatusList());

        $domain = $this->request->param('domain');
        $this->assignconfig('domain', $domain);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where2 = array();
            $domain = $this->request->param('domain');
            if($domain >0){
                $where2['domain'] = $domain;
            }

            $where3['status'] = 'hidden';
            $list = $this->model
                ->where($where)
                ->where($where3)
//                ->where($where2)
                ->order($sort, $order)
                ->paginate($limit);
            $lists = $list->items();
            if($lists){
                foreach ($lists as $k=>$v){
                    $accounturl = Db::name('fedition_accounturl')->where('id', '=', $v['account_address'])->find();
                    if($accounturl){
                        $lists[$k]['account_address_name'] = $accounturl['name'];
                    }else{
                        $lists[$k]['account_address_name'] = '店铺未设置';
                    }
                    $domain = Db::name('dns_list')->where('id', '=', $v['domain'])->find();
                    if($domain){
                        $lists[$k]['domain_name'] = $domain['name'];
                    }else{
                        $lists[$k]['domain_name'] = '域名未设置';
                    }
                    $admin = Db::name('admin')->where('id', '=', $v['admin_id'])->find();
                    if($admin){
                        $lists[$k]['admin_name'] = $admin['nickname'];
                    }else{
                        $lists[$k]['admin_name'] = '管理员未设置';
                    }
                    if (!empty($v['manual'])) {
                        $lists[$k]['admin_name'] = '其他';
                    }
                    $zbalances = array();
                    if(empty($v['zeuro']) && empty($v['zpound']) && empty($v['zdollar'])){
                        $lists[$k]['zbalance'] = '暂无';
                    }else{
                        if(!empty($v['zeuro']) && (int)$v['zeuro'] !== 0){
                            $zbalances[] = '欧元：'.$v['zeuro'];
                        }
                        if(!empty($v['zpound']) && (int)$v['zpound'] !== 0){
                            $zbalances[] = '英镑：'.$v['zpound'];
                        }
                        if(!empty($v['zdollar']) && (int)$v['zdollar'] !== 0){
                            $zbalances[] = '美元：'.$v['zdollar'];
                        }
                        $lists[$k]['zbalance'] = implode("\n",$zbalances);
                    }
                }
            }

            $result = array("total" => $list->total(), "rows" => $lists);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (empty($params['admin_id'])) {
                $this->error('归属人不能为空，请重新填写');
            }
            $admin_id = $params['admin_id'];
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();

                //查看email是否重复
                $emails = Db::name('fedition_account')->where('email',$params['email'])->find();
                if (!empty($emails)) {
                    $this->error('email重复，请重新填写');
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    //判断域名是否被使用
//                    $domain_judge = $this->account_domain_judge($params['domain']);
//                    if($domain_judge == false){
//                        $this->error(__('该域名已被使用'));
//                    }
                    if(!empty($params['payment_method'])){
                        $params['payment_method'] = implode(',',$params['payment_method']);
                    }
                    $numbername = $this->add_numbername($params['numbertype']);
                    $params['numbername'] = $numbername['numbername'];
                    $params['country'] = $numbername['country'];

                    $params['admin_id'] = $admin_id;
                    $params['admin_operate'] = $this->auth->id;
                    $params['type_operate'] = 1;
                    $params['createtime'] = time();
                    $params['updatetime'] = time();
                    $result = $this->model->allowField(true)->insertGetId($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //绑定域名后 修改域名状态
//                    $account_usage_status = $this->account_usage_status($params['domain'],'');
                    //type 类型 operation具体操作
                    $this->add_virtualmachine_log(4,$result,1);
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $paymentMethodList = ['自动支付' => __('自动支付'), '手动支付' => __('手动支付')];
        $this->view->assign("paymentMethodList",$paymentMethodList);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();

                if(!empty($params['payment_method'])){
                    $params['payment_method'] = implode(',',$params['payment_method']);
                }
                if (!empty($params['iptime'])) {
                    $params['iptime'] = strtotime($params['iptime']);
                }
                $numbername = $this->add_numbername($params['numbertype']);
                $params['numbername'] = $numbername['numbername'];
                $params['country'] = $numbername['country'];
                //状态正常前需要填写ip等信息
                $oldstatus = $row['status'];
                if ($oldstatus !== 'normal' && $params['status'] == 'normal' ) {
                    if (empty($params['ip']) || empty($params['ippassword'])) {
                        $this->error(__('账户激活使用前需要填写ip跟ip密码'));
                    }
                }
                if ($params['status'] == 'normal') {
                    $params['type_operate'] = 1;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    //判断域名是否被使用
//                    $domain_judge = $this->account_domain_judge($params['domain']);
//                    if($domain_judge == false){
//                        $this->error(__('该域名已被使用'));
//                    }
                    //查询数据是否有重复
//                    if(!empty($params['amount'])){
//                        $amount1 = json_decode($params['amount'],true);
//                        $type = 'type';
//                        $amount2 = $this->assoc_unique($amount1,$type);
//                        if(count($amount1) !== count($amount2)){
//                            $this->error(__('账户余额类型重复，请检查'));
//                        }
//                    }
//                    $data['amount'] = $params['amount'];
                    $result = $row->allowField(true)->save($params);
//                    $data['id'] = $ids;
//                    $result = $this->add_dnschannel($data,2);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //绑定域名后 修改域名状态
//                    $account_usage_status = $this->account_usage_status($params['domain'],$olddomain);
                    //type 类型 operation具体操作
                    $this->add_virtualmachine_log(4,$ids,2);
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
//        $iptime = strtotime('yesterday');
//        $this->view->assign("iptime", $iptime);
        $this->view->assign("row", $row);
        //域名
//        $websitedns = Db::name('fedition_balance')
//            ->where('account_id', '=', $row['id'])
//            ->select();
//        $amount = array();
//        foreach ($websitedns as $k=>$v){
//            $data['type'] = $v['moneytype'];
//            $data['amount'] = $v['amount'];
//            $amount[] = $data;
//        }
//        if(empty($amount)){
//            $amount = '';
//        }else{
//            $amount = json_encode($amount);
//        }
//        $this->view->assign("amount", $amount);
        $paymentMethodList = ['自动支付' => __('自动支付'), '手动支付' => __('手动支付')];
        $this->view->assign("paymentMethodList",$paymentMethodList);
        return $this->view->fetch();
    }

    /**
     * @param $arr
     * @param $key 重复字段
     * @return mixed
     * 根据某个字段去除重复数据 取一条
     */
//    function assoc_unique($arr,$key) {
//        $tmp_arr = array();
//        foreach($arr as $k => $v) {
//            if(in_array($v[$key], $tmp_arr)) {
//                unset($arr[$k]);
//            } else {
//                $tmp_arr[] = $v[$key];
//            }
//        }
//        sort($arr);
//        return $arr;
//    }
    /**
     * @return add_dnschannel
     */
//    public function add_dnschannel($params,$type)
//    {
//        $amount = json_decode($params['amount'],true);
//        if($type == 2){
//            $this->del_dnschannel($params['id']);
//        }
//        $this->handle_amount($amount,$params['id']);
//        return true;
//    }
    /**
     * @return del_dnschannel
     */
//    public function del_dnschannel($id)
//    {
//        $return = $typechannel = Db::name('fedition_balance')
//            ->where('account_id', '=', $id)
//            ->delete();
//        return $return;
//    }

    /**
     * @return handle_amount
     */
//    public function handle_amount($amount,$id)
//    {
//        $return = false;
//        if(!empty($amount)){
//            foreach ($amount as $k=>$v){
//                $datatype['account_id'] = $id;
//                $datatype['moneytype'] = $v['type'];
//                $datatype['amount'] = $v['amount'];
//                $datatype['createtime'] = time();
//                $datatype['updatetime'] = time();
//                $return = Db::name('fedition_balance')->insert($datatype);
//                if($return){
//                    //同步更新
//                    $moneytype = Db::name('fedition_moneytype')->where('id', '=', $v['type'])->find();
//                    if($moneytype['name'] == '美金'){
//                        Db::name('fedition_account')->where('id', '=', $id)->update(['zdollar' => $v['amount']]);
//                    }elseif ($moneytype['name'] == '英镑'){
//                        Db::name('fedition_account')->where('id', '=', $id)->update(['zpound' => $v['amount']]);
//                    }elseif ($moneytype['name'] == '欧元'){
//                        Db::name('fedition_account')->where('id', '=', $id)->update(['zeuro' => $v['amount']]);
//                    }
//                }
//            }
//            //type 类型 operation具体操作
//            $this->add_operation_log(3,$id,1);
//        }
//        return $return;
//    }

    /**
     * add_number
     */
    public function add_number()
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $numbertype = $this->request->post("numbertype");
        $id = $this->request->post("id");
        if(!empty($numbertype)) {
            //如果是修改 则跟之前相同时不改变
            if(!empty($id)) {
                $account_e = Db::name('fedition_account')
                    ->where('id', $id)
                    ->find();
                if ($account_e['numbertype'] == $numbertype && !empty($account_e['numberid'])) {
                    $data['numbertype'] = $account_e['numbertype'];
                    $data['numberid'] = $account_e['numberid'];
                    $data['number'] = $account_e['number'];
                    $this->success('无需修改','', $data);
                }
            }
            $account = Db::name('fedition_account')
                ->where('numbertype', '=', $numbertype)
                ->order('numberid desc')
                ->find();
            if($account){
                $data['numbertype'] = $numbertype;
                $data['numberid'] = $account['numberid'] + 1;
                $data['number'] = $data['numbertype'].'00'.$data['numberid'];
            }else{
                $data['numbertype'] = $numbertype;
                $data['numberid'] = 1;
                $data['number'] = $data['numbertype'].'00'.$data['numberid'];
            }
            $this->success('返回数据','', $data);
        }else{
            $this->error(__('参数错误'));
        }
    }
}
